/**
 * 智能图片定位系统JavaScript
 */

class IntelligentPositioning {
    constructor() {
        this.currentTemplate = null;
        this.jsonData = null;
        this.analysisResult = null;
        this.canvas = null;
        this.ctx = null;
        this.templateLayers = [];
        this.selectedLayerIndex = -1;
        this.layerColorAdjustments = {};
        this.selectedImageIndex = -1;
        this.imageRotations = {};
        this.imageColorAdjustments = {};
        this.isDragging = false;
        this.isRotating = false;
        this.isResizing = false;
        this.resizeMode = null;
        this.dragStart = { x: 0, y: 0 };
        this.controlPoints = [];
        
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.initCanvas();
    }
    
    bindEvents() {
        // 模板选择
        $('#templateSelect').on('change', (e) => {
            const templateId = $(e.target).val();
            if (templateId) {
                this.loadTemplate(templateId);
            } else {
                this.currentTemplate = null;
                this.updateAnalyzeButton();
            }
        });
        
        // JSON文件上传
        $('#jsonFile').on('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                this.uploadJsonFile(file);
            }
        });
        
        // 分析按钮
        $('#analyzeBtn').on('click', () => {
            this.startIntelligentAnalysis();
        });
        
        // 保存智能项目
        $('#saveIntelligentProject').on('click', () => {
            this.saveIntelligentProject();
        });
        
        // 导出结果
        $('#exportIntelligentResult').on('click', () => {
            this.exportIntelligentResult();
        });
        
        // 导出格式变化时显示/隐藏图层保留选项
        $('#intelligentExportFormat').on('change', (e) => {
            const format = $(e.target).val();
            const preserveLayersContainer = $('#intelligentPreserveLayersContainer');
            if (format === 'tif' || format === 'tiff' || format === 'psd') {
                preserveLayersContainer.show();
                if (format === 'psd') {
                    $('#intelligentPreserveLayers').prop('checked', true);
                }
            } else {
                preserveLayersContainer.hide();
                $('#intelligentPreserveLayers').prop('checked', false);
            }
        });
        
        // 手动适配区域
        $('#adaptToRegions').on('click', () => {
            this.manualAdaptToRegions();
        });
        
        // 重新分析
        $('#resetAnalysis').on('click', () => {
            this.resetAnalysis();
        });
        
        // 测试功能按钮
        $('#testFeatures').on('click', () => {
            this.testNewFeatures();
        });
        
        // 批量上传文件选择
        $('#batchImageUpload').on('change', (e) => {
            const files = e.target.files;
            if (files.length > 0) {
                this.handleBatchFileSelection(files);
            }
        });
        
        // 处理批量上传
        $('#processBatchUpload').on('click', () => {
            this.processBatchUpload();
        });
        
        // 区域切换控制
        $('#prevRegionBtn').on('click', () => {
            this.switchToPreviousRegion();
        });
        
        $('#nextRegionBtn').on('click', () => {
            this.switchToNextRegion();
        });
        
        $('#highlightCurrentRegion').on('click', () => {
            this.highlightCurrentRegion();
        });
        
        $('#replaceCurrentImage').on('click', () => {
            this.replaceCurrentImage();
        });
        
        $('#removeCurrentImage').on('click', () => {
            this.removeCurrentImage();
        });
        
        // ========== 图层颜色调整事件 - 已隐藏 ==========
        /*
        $('#layerColorPicker').on('change', (e) => {
            $('#layerColorInput').val($(e.target).val());
            this.previewLayerColorChanges();
        });
        
        $('#layerColorInput').on('input', (e) => {
            const colorValue = $(e.target).val();
            if (/^#[0-9A-F]{6}$/i.test(colorValue)) {
                $('#layerColorPicker').val(colorValue);
                this.previewLayerColorChanges();
            }
        });
        
        $('#applyColorChanges').on('click', () => {
            this.applyLayerColorChanges();
        });
        
        $('#resetLayerColor').on('click', () => {
            this.resetLayerColorChanges();
        });
        */
        
        // ========== 图片交互事件 ==========
        
        // 画布鼠标事件
        if (this.canvas) {
            this.canvas.addEventListener('mousedown', this.onCanvasMouseDown.bind(this));
            this.canvas.addEventListener('mousemove', this.onCanvasMouseMove.bind(this));
            this.canvas.addEventListener('mouseup', this.onCanvasMouseUp.bind(this));
            this.canvas.addEventListener('mouseleave', this.onCanvasMouseLeave.bind(this));
        }
        
        // 旋转控制按钮 - 使用事件委托
        $(document).on('click', '#rotateImage15Left', () => this.rotateSelectedImage(-15));
        $(document).on('click', '#rotateImage90Left', () => this.rotateSelectedImage(-90));
        $(document).on('click', '#rotateImage90Right', () => this.rotateSelectedImage(90));
        $(document).on('click', '#rotateImage15Right', () => this.rotateSelectedImage(15));
        $(document).on('click', '#resetImageRotation', () => this.resetSelectedImageRotation());
        
        // 鼠标滚轮旋转
        $('#intelligentCanvas').on('wheel', (e) => {
            if (this.selectedImageIndex >= 0) {
                e.preventDefault();
                const delta = e.originalEvent.deltaY > 0 ? -5 : 5;
                this.rotateSelectedImage(delta);
            }
        });
    }
    
    initCanvas() {
        this.canvas = document.getElementById('intelligentCanvas');
        if (this.canvas) {
            this.ctx = this.canvas.getContext('2d');
        }
    }
    
    async loadTemplate(templateId) {
        try {
            APP_UTILS.showLoading('加载模板...');
            
            const response = await APP_AJAX.get(`/api/template/${templateId}/regions`);
            
            this.currentTemplate = response.template;
            this.currentRegions = response.regions || [];
            this.templateLayers = response.template_layers || [];
            
            console.log('模板加载完成:', {
                template: this.currentTemplate,
                regions: this.currentRegions,
                layers: this.templateLayers
            });
            
            this.updateAnalyzeButton();
            this.displayGarmentParts();
            this.loadTemplatePreview();  // 添加模板预览
            
            // 显示图层信息 - 已隐藏
            // this.displayTemplateLayers();
            
            APP_UTILS.hideLoading();
        } catch (error) {
            APP_UTILS.hideLoading();
            APP_UTILS.showError('加载模板失败: ' + (error.error || '未知错误'));
        }
    }
    
    async uploadJsonFile(file) {
        try {
            APP_UTILS.showLoading('上传JSON文件...');
            
            const response = await APP_AJAX.upload('/upload_json', file);
            
            if (response.success) {
                this.jsonData = response.data;
                console.log('JSON文件上传成功:', this.jsonData);
                
                this.updateAnalyzeButton();
                APP_UTILS.showSuccess('JSON文件上传成功');
            } else {
                APP_UTILS.showError(response.error || '上传失败');
            }
            
            APP_UTILS.hideLoading();
        } catch (error) {
            APP_UTILS.hideLoading();
            APP_UTILS.showError('上传失败: ' + (error.error || '未知错误'));
        }
    }
    
    updateAnalyzeButton() {
        const canAnalyze = this.currentTemplate && this.jsonData;
        $('#analyzeBtn').prop('disabled', !canAnalyze);
    }
    
    displayGarmentParts() {
        const container = $('#garmentParts');
        
        if (!this.templateLayers || this.templateLayers.length === 0) {
            container.html(`
                <div class="text-muted text-center py-3">
                    <i class="bi bi-exclamation-triangle"></i>
                    <div>未检测到服装部位</div>
                </div>
            `);
            return;
        }
        
        let html = '';
        this.templateLayers.forEach(layer => {
            const icon = layer.is_group ? 'bi-folder' : 'bi-image';
            const partType = this.detectGarmentPart(layer.name);
            const badgeClass = partType ? 'bg-success' : 'bg-secondary';
            
            html += `
                <div class="garment-part-item ${partType ? 'detected' : ''}">
                    <div class="d-flex align-items-center">
                        <i class="bi ${icon} me-2"></i>
                        <div class="flex-grow-1">
                            <div class="fw-medium">${layer.name}</div>
                            <small class="text-muted">${layer.type}</small>
                        </div>
                        ${partType ? `<span class="badge ${badgeClass}">${partType}</span>` : ''}
                    </div>
                </div>
            `;
        });
        
        container.html(html);
    }
    
    detectGarmentPart(layerName) {
        const name = layerName.toLowerCase();
        
        if (name.includes('前') || name.includes('胸') || name.includes('front') || name.includes('chest')) {
            return '前胸';
        } else if (name.includes('后') || name.includes('背') || name.includes('back')) {
            return '后背';
        } else if (name.includes('左袖') || name.includes('left') && name.includes('sleeve')) {
            return '左袖';
        } else if (name.includes('右袖') || name.includes('right') && name.includes('sleeve')) {
            return '右袖';
        } else if (name.includes('领') || name.includes('collar') || name.includes('neck')) {
            return '领口';
        } else if (name.includes('袖') || name.includes('sleeve')) {
            return '袖子';
        }
        
        return null;
    }
    
    async startIntelligentAnalysis() {
        if (!this.currentTemplate || !this.jsonData) {
            APP_UTILS.showError('请先选择模板并上传JSON文件');
            return;
        }
        
        try {
            APP_UTILS.showLoading('智能分析中...');
            
            const response = await APP_AJAX.post('/api/intelligent_analysis', {
                template_id: this.currentTemplate.id,
                json_data: this.jsonData
            });
            
            if (response.success) {
                this.analysisResult = response.result;
                this.displayAnalysisResult();
                this.renderIntelligentPreview();
                
            $('#saveIntelligentProject').prop('disabled', false);
            $('#exportIntelligentResult').prop('disabled', false);
            $('#adaptToRegions').prop('disabled', false);
                
                APP_UTILS.showSuccess('智能分析完成');
            } else {
                APP_UTILS.showError(response.error || '分析失败');
            }
            
            APP_UTILS.hideLoading();
        } catch (error) {
            APP_UTILS.hideLoading();
            APP_UTILS.showError('分析失败: ' + (error.error || '未知错误'));
        }
    }
    
    displayAnalysisResult() {
        if (!this.analysisResult) return;
        
        const result = this.analysisResult;
        
        // 显示分析统计
        $('#analysisContent').html(`
            <div class="analysis-stats">
                <div class="row g-2 text-center">
                    <div class="col-6">
                        <div class="bg-primary text-white p-2 rounded">
                            <div class="h5 mb-0">${result.total_images || 0}</div>
                            <small>检测图片</small>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="bg-success text-white p-2 rounded">
                            <div class="h5 mb-0">${Object.keys(result.garment_analysis?.garment_parts || {}).length}</div>
                            <small>识别部位</small>
                        </div>
                    </div>
                </div>
            </div>
        `);
        
        $('#analysisResult').show();
        
        // 显示检测到的图片
        this.displayDetectedImages();
        
        // 显示智能建议
        this.displaySuggestions();
        
        // 添加上传入口
        this.createUploadEntries();
        
        // 显示批量上传选项（如果识别出多个图片）
        if (result.total_images > 1) {
            $('#batchUploadSection').show();
        }
        
        // 显示图片操作控制器
        $('#imageControlGroup').show();
        
        // 显示测试功能按钮（开发期间）
        $('#testFeatures').show();
        
        // 初始化区域切换控制
        this.initRegionSwitchControl();
    }
    
    displayDetectedImages() {
        const container = $('#detectedImages');
        
        if (!this.analysisResult?.positioning_result?.matches) {
            container.html(`
                <div class="text-muted text-center py-3">
                    <i class="bi bi-image-alt"></i>
                    <div>未检测到图片</div>
                </div>
            `);
            return;
        }
        
        let html = '';
        this.analysisResult.positioning_result.matches.forEach((match, index) => {
            const confidence = Math.round(match.confidence * 100);
            const badgeClass = confidence > 70 ? 'bg-success' : confidence > 50 ? 'bg-warning' : 'bg-danger';
            
            html += `
                <div class="image-item">
                    <div class="d-flex align-items-center">
                        <img src="/proxy_image?url=${encodeURIComponent(match.image_url)}" 
                             alt="图片 ${index + 1}" class="me-2">
                        <div class="flex-grow-1">
                            <div class="fw-medium">图片 ${index + 1}</div>
                            <small class="text-muted">${match.suggested_part}</small>
                            <div>
                                <span class="badge ${badgeClass} confidence-badge">${confidence}%</span>
                            </div>
                        </div>
                    </div>
                    <div class="mt-2">
                        <small class="text-muted">
                            位置: (${match.optimal_position.x}, ${match.optimal_position.y})
                        </small>
                    </div>
                </div>
            `;
        });
        
        container.html(html);
    }
    
    displaySuggestions() {
        const container = $('#suggestions');
        
        if (!this.analysisResult?.positioning_result?.matches) {
            return;
        }
        
        let html = '';
        this.analysisResult.positioning_result.matches.forEach((match, index) => {
            html += `
                <div class="suggestion-item">
                    <div class="fw-medium">图片 ${index + 1}</div>
                    <div class="small text-muted">${match.reasoning}</div>
                    <div class="small">
                        建议位置: ${match.suggested_part}
                        <span class="ms-2 text-primary">(${Math.round(match.confidence * 100)}%)</span>
                    </div>
                </div>
            `;
        });
        
        container.html(html);
    }
    
    createUploadEntries() {
        if (!this.analysisResult?.positioning_result?.matches) return;
        
        const matches = this.analysisResult.positioning_result.matches;
        console.log('创建上传入口，区域数:', matches.length);
        
        // 在检测到的图片区域添加上传入口
        let uploadHtml = '<div class="mt-3"><h6 class="text-muted mb-2">上传定制图片</h6>';
        
        matches.forEach((match, index) => {
            uploadHtml += `
                <div class="upload-entry mb-3 p-3 border rounded">
                    <div class="d-flex align-items-center mb-2">
                        <span class="badge bg-primary me-2">${index + 1}</span>
                        <strong>${match.suggested_part}</strong>
                        <small class="text-muted ms-2">位置: (${match.optimal_position.x}, ${match.optimal_position.y})</small>
                    </div>
                    
                    <div class="mb-2">
                        <input type="file" class="form-control form-control-sm" 
                               id="customImage_${index}" 
                               accept=".png,.jpg,.jpeg,.gif,.webp"
                               data-index="${index}">
                    </div>
                    
                    <div class="upload-preview" id="preview_${index}" style="display: none;">
                        <img src="" alt="预览" class="img-thumbnail" style="max-width: 100px; max-height: 100px;">
                        <button class="btn btn-sm btn-outline-danger ms-2" onclick="window.intelligentPositioning.removeUploadedImage(${index})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                    
                    <div class="mt-2">
                        <small class="text-muted">
                            建议尺寸: ${match.optimal_position.width || 300} × ${match.optimal_position.height || 300}
                        </small>
                    </div>
                </div>
            `;
        });
        
        uploadHtml += '</div>';
        
        $('#detectedImages').append(uploadHtml);
        
        // 绑定上传事件
        this.bindUploadEvents();
    }
    
    bindUploadEvents() {
        $('[id^="customImage_"]').on('change', (e) => {
            const input = e.target;
            const index = $(input).data('index');
            const file = input.files[0];
            
            if (file) {
                this.handleImageUpload(index, file);
            }
        });
    }
    
    handleImageUpload(index, file) {
        console.log(`上传图片 ${index + 1}:`, file.name);
        
        // 创建预览
        const reader = new FileReader();
        reader.onload = (e) => {
            const previewContainer = $(`#preview_${index}`);
            const img = previewContainer.find('img');
            
            img.attr('src', e.target.result);
            previewContainer.show();
            
            // 保存上传的图片信息
            if (!this.uploadedImages) {
                this.uploadedImages = {};
            }
            
            const match = this.analysisResult.positioning_result.matches[index];
            
            // 初始化时强制适配定制区域
            if (match && match.optimal_position) {
                console.log(`为图片${index + 1}初始化适配定制区域...`);
                // 初始化时强制适配，不受距离限制
                this.adaptToNearestRegion(match.optimal_position, true);
            }
            
            this.uploadedImages[index] = {
                file: file,
                dataUrl: e.target.result,
                match: match
            };
            
            // 更新预览
            this.updatePreviewWithUploadedImages();
            
            console.log(`图片 ${index + 1} 上传成功`);
        };
        
        reader.readAsDataURL(file);
    }
    
    removeUploadedImage(index) {
        if (this.uploadedImages && this.uploadedImages[index]) {
            delete this.uploadedImages[index];
            
            // 清空预览
            const previewContainer = $(`#preview_${index}`);
            previewContainer.hide();
            previewContainer.find('img').attr('src', '');
            
            // 清空上传输入
            $(`#customImage_${index}`).val('');
            
            // 更新预览
            this.updatePreviewWithUploadedImages();
            
            console.log(`移除图片 ${index + 1}`);
        }
    }
    
    updatePreviewWithUploadedImages() {
        // 重新渲染模板预览
        this.renderTemplatePreview();
        
        // 添加上传的图片
        if (this.uploadedImages) {
            Object.keys(this.uploadedImages).forEach(index => {
                const imageData = this.uploadedImages[index];
                const match = imageData.match;
                
                // 加载并绘制上传的图片
                const img = new Image();
                img.onload = () => {
                    const pos = match.optimal_position;
                    const x = pos.x * this.displayScale;
                    const y = pos.y * this.displayScale;
                    const width = (pos.width || 300) * this.displayScale;
                    const height = (pos.height || 300) * this.displayScale;
                    
                    // 绘制上传的图片
                    this.ctx.drawImage(img, x, y, width, height);
                    
                    // 绘制边框和选择状态
                    if (this.selectedImageIndex == index) {
                        this.ctx.strokeStyle = '#ff6b6b';
                        this.ctx.lineWidth = 4;
                        this.ctx.setLineDash([5, 5]);
                    } else {
                        this.ctx.strokeStyle = '#28a745';
                        this.ctx.lineWidth = 3;
                        this.ctx.setLineDash([]);
                    }
                    this.ctx.strokeRect(x, y, width, height);
                    this.ctx.setLineDash([]);
                    
                    // 绘制调整手柄（四个角）
                    if (this.selectedImageIndex == index) {
                        this.drawResizeHandles(x, y, width, height);
                    }
                    
                    // 绘制标签
                    this.ctx.fillStyle = 'rgba(40, 167, 69, 0.9)';
                    this.ctx.fillRect(x, y - 25, 250, 25);
                    this.ctx.fillStyle = '#ffffff';
                    this.ctx.font = `bold ${Math.max(10, 12 * this.displayScale)}px Arial`;
                    this.ctx.fillText(`图片${parseInt(index) + 1}: ${match.suggested_part} [${Math.round(width/this.displayScale)}×${Math.round(height/this.displayScale)}]`, x + 5, y - 8);
                };
                
                img.src = imageData.dataUrl;
            });
        }
    }
    
    async renderIntelligentPreview() {
        if (!this.canvas || !this.currentTemplate || !this.analysisResult) return;
        
        console.log('开始渲染智能分析结果');
        
        // 先渲染基础模板
        this.renderTemplatePreview();
        
        // 等待上传的图片渲染完成
        await this.renderUploadedImages();
        
        // 最后渲染智能定位结果
        this.addIntelligentResults();
    }
    
    async renderUploadedImages() {
        if (!this.uploadedImages || !this.ctx) return;
        
        console.log('渲染上传的图片', Object.keys(this.uploadedImages).length);
        
        // 使用Promise.all确保所有图片都加载完成后再渲染
        const imagePromises = [];
        
        Object.keys(this.uploadedImages).forEach(index => {
            const imageData = this.uploadedImages[index];
            const match = imageData.match;
            const rotation = this.imageRotations[index] || 0;
            
            const promise = new Promise((resolve) => {
                const img = new Image();
                img.onload = () => {
                    resolve({
                        img: img,
                        index: index,
                        match: match,
                        rotation: rotation
                    });
                };
                img.onerror = () => {
                    console.error(`图片加载失败: ${index}`);
                    resolve(null);
                };
                img.src = imageData.dataUrl;
            });
            
            imagePromises.push(promise);
        });
        
        try {
            const loadedImages = await Promise.all(imagePromises);
            
            // 绘制所有加载成功的图片
            loadedImages.forEach(imageInfo => {
                if (!imageInfo) return;
                
                const { img, index, match, rotation } = imageInfo;
                const imageData = this.uploadedImages[index];
                const pos = match.optimal_position;
                const x = pos.x * this.displayScale;
                const y = pos.y * this.displayScale;
                const width = (pos.width || 300) * this.displayScale * (imageData.scaleX || 1.0);
                const height = (pos.height || 300) * this.displayScale * (imageData.scaleY || 1.0);
                
                // 保存画布状态
                this.ctx.save();
                
                // 如果有旋转，应用旋转变换
                if (rotation !== 0) {
                    const centerX = x + width / 2;
                    const centerY = y + height / 2;
                    this.ctx.translate(centerX, centerY);
                    this.ctx.rotate(rotation * Math.PI / 180);
                    this.ctx.translate(-centerX, -centerY);
                }
                
                // 绘制图片
                this.ctx.drawImage(img, x, y, width, height);
                
                // 如果是选中的图片，绘制选择框和控制点
                if (parseInt(index) === this.selectedImageIndex) {
                    this.ctx.strokeStyle = '#ffc107';
                    this.ctx.lineWidth = 3;
                    this.ctx.setLineDash([5, 5]);
                    this.ctx.strokeRect(x - 2, y - 2, width + 4, height + 4);
                    
                    // 绘制缩放控制点
                    this.drawResizeHandles(x, y, width, height);
                }
                
                // 恢复画布状态
                this.ctx.restore();
                
                console.log(`渲染图片 ${index}: 位置(${x}, ${y}), 尺寸(${width}x${height}), 旋转${rotation}°`);
            });
            
        } catch (error) {
            console.error('图片渲染失败:', error);
        }
    }
    
    addIntelligentResults() {
        if (!this.ctx || !this.analysisResult) return;
        
        console.log('添加智能定位结果到预览');
        
        // 检查是否有上传的图片，如果有则不显示定位方框
        const hasUploadedImages = this.uploadedImages && Object.keys(this.uploadedImages).length > 0;
        
        if (hasUploadedImages) {
            console.log('🖼️ 检测到已上传图片，跳过定位方框显示以避免冲突');
            
            // 只显示未上传图片的定位区域
            this.analysisResult.positioning_result.matches.forEach((match, index) => {
                if (!this.uploadedImages[index]) {
                    // 只为没有上传图片的区域显示虚线框
                    const pos = match.optimal_position;
                    const x = pos.x * this.displayScale;
                    const y = pos.y * this.displayScale;
                    const width = (pos.width || 200) * this.displayScale;
                    const height = (pos.height || 200) * this.displayScale;
                    
                    // 绘制虚线边框（更轻微的提示）
                    this.ctx.strokeStyle = 'rgba(40, 167, 69, 0.5)';
                    this.ctx.lineWidth = 1;
                    this.ctx.setLineDash([3, 3]);
                    this.ctx.strokeRect(x, y, width, height);
                    
                    // 添加小标签
                    this.ctx.fillStyle = 'rgba(40, 167, 69, 0.7)';
                    this.ctx.font = '10px Arial';
                    this.ctx.fillText(`等待上传: ${match.suggested_part}`, x + 2, y + 12);
                }
            });
            return;
        }
        
        // 没有上传图片时，显示完整的智能定位结果
        this.analysisResult.positioning_result.matches.forEach((match, index) => {
            const pos = match.optimal_position;
            const x = pos.x * this.displayScale;
            const y = pos.y * this.displayScale;
            const width = (pos.width || 200) * this.displayScale;
            const height = (pos.height || 200) * this.displayScale;
            
            // 绘制半透明的绿色区域标记
            this.ctx.fillStyle = 'rgba(40, 167, 69, 0.2)';
            this.ctx.fillRect(x, y, width, height);
            
            // 绘制绿色边框
            this.ctx.strokeStyle = '#28a745';
            this.ctx.lineWidth = 3;
            this.ctx.setLineDash([]);
            this.ctx.strokeRect(x, y, width, height);
            
            // 绘制标签背景
            this.ctx.fillStyle = 'rgba(40, 167, 69, 0.8)';
            this.ctx.fillRect(x, y - 25, Math.max(120, width), 25);
            
            // 绘制标签文字
            this.ctx.fillStyle = '#ffffff';
            this.ctx.font = `bold ${Math.max(10, 12 * this.displayScale)}px Arial`;
            this.ctx.fillText(`智能定位: ${match.suggested_part}`, x + 5, y - 8);
        });
        
        console.log('智能结果渲染完成');
    }
    
    async saveIntelligentProject() {
        if (!this.analysisResult) {
            APP_UTILS.showError('请先进行智能分析');
            return;
        }
        
        if (!this.uploadedImages || Object.keys(this.uploadedImages).length === 0) {
            APP_UTILS.showError('请先上传定制图片');
            return;
        }
        
        const projectName = prompt('请输入智能项目名称:', `智能定位_${new Date().toLocaleDateString()}`);
        if (!projectName) return;
        
        try {
            APP_UTILS.showLoading('保存智能项目...');
            
            // 准备保存数据
            const saveData = this.prepareSaveData();
            
            const response = await APP_AJAX.post('/api/save_intelligent_project', {
                project_name: projectName,
                template_id: this.currentTemplate.id,
                analysis_result: this.analysisResult,
                uploaded_images: this.uploadedImages,
                customization_data: saveData
            });
            
            if (response.success) {
                APP_UTILS.showSuccess('智能项目保存成功');
                this.projectId = response.project_id;
            } else {
                APP_UTILS.showError(response.error || '保存失败');
            }
            
            APP_UTILS.hideLoading();
        } catch (error) {
            APP_UTILS.hideLoading();
            APP_UTILS.showError('保存失败: ' + (error.error || '未知错误'));
        }
    }
    
    drawResizeHandles(x, y, width, height) {
        const handleSize = 8;
        this.ctx.fillStyle = '#ff6b6b';
        
        // 四个角的调整手柄
        this.ctx.fillRect(x - handleSize/2, y - handleSize/2, handleSize, handleSize);
        this.ctx.fillRect(x + width - handleSize/2, y - handleSize/2, handleSize, handleSize);
        this.ctx.fillRect(x - handleSize/2, y + height - handleSize/2, handleSize, handleSize);
        this.ctx.fillRect(x + width - handleSize/2, y + height - handleSize/2, handleSize, handleSize);
        
        // 添加白色边框
        this.ctx.strokeStyle = '#ffffff';
        this.ctx.lineWidth = 1;
        this.ctx.strokeRect(x - handleSize/2, y - handleSize/2, handleSize, handleSize);
        this.ctx.strokeRect(x + width - handleSize/2, y - handleSize/2, handleSize, handleSize);
        this.ctx.strokeRect(x - handleSize/2, y + height - handleSize/2, handleSize, handleSize);
        this.ctx.strokeRect(x + width - handleSize/2, y + height - handleSize/2, handleSize, handleSize);
    }
    
    prepareSaveData() {
        // 准备保存数据，包含用户上传的图片信息
        const customizationData = {
            regions: {}
        };
        
        if (this.uploadedImages) {
            Object.keys(this.uploadedImages).forEach(index => {
                const imageData = this.uploadedImages[index];
                const match = imageData.match;
                
                const element = {
                    image_file: imageData.file,  // 实际文件
                    user_placement_data: {
                        position: {
                            x: match.optimal_position.x,
                            y: match.optimal_position.y
                        },
                        dimension: {
                            width: match.optimal_position.width || 300,
                            height: match.optimal_position.height || 300
                        },
                        scale: {
                            scale_x: imageData.scaleX || 1.0, 
                            scale_y: imageData.scaleY || 1.0
                        },
                        angle_of_rotation: this.imageRotations[index] || 0
                    },
                    intelligent_info: {
                        suggested_part: match.suggested_part,
                        confidence: match.confidence,
                        reasoning: match.reasoning
                    }
                };
                
                const regionIndex = match.optimal_position.region_id || index;
                if (!customizationData.regions[regionIndex]) {
                    customizationData.regions[regionIndex] = {elements: []};
                }
                
                customizationData.regions[regionIndex].elements.push(element);
            });
        }
        
        return customizationData;
    }
    
    addCanvasDragFunctionality() {
        if (!this.canvas) {
            console.error('⚠️ Canvas不存在，无法添加拖拽功能');
            return;
        }
        
        // 初始化状态变量
        this.selectedImageIndex = null;
        this.isDragging = false;
        this.isResizing = false;
        this.resizeHandle = null;
        this.dragStart = {x: 0, y: 0};
        this.originalSize = {width: 0, height: 0};
        
        // 移除旧的事件监听器（避免重复添加）
        this.canvas.removeEventListener('mousedown', this.mouseDownHandler);
        this.canvas.removeEventListener('mousemove', this.mouseMoveHandler);
        this.canvas.removeEventListener('mouseup', this.mouseUpHandler);
        
        // 创建绑定的事件处理器
        this.mouseDownHandler = (e) => this.onCanvasMouseDown(e);
        this.mouseMoveHandler = (e) => this.onCanvasMouseMove(e);
        this.mouseUpHandler = (e) => this.onCanvasMouseUp(e);
        
        // 添加事件监听器
        this.canvas.addEventListener('mousedown', this.mouseDownHandler);
        this.canvas.addEventListener('mousemove', this.mouseMoveHandler);
        this.canvas.addEventListener('mouseup', this.mouseUpHandler);
        
        // 添加鼠标离开事件（防止拖拽卡住）
        this.canvas.addEventListener('mouseleave', () => {
            if (this.isDragging || this.isResizing) {
                this.onCanvasMouseUp();
            }
        });
        
        console.log('✅ 添加了画布拖拽功能');
        
        // 添加调试信息
        this.canvas.addEventListener('click', (e) => {
            console.log('画布点击事件触发', {
                x: e.clientX - this.canvas.getBoundingClientRect().left,
                y: e.clientY - this.canvas.getBoundingClientRect().top,
                uploadedImages: this.uploadedImages ? Object.keys(this.uploadedImages).length : 0
            });
        });
    }
    
    onCanvasMouseDown(e) {
        console.log('✅ onCanvasMouseDown 被调用', {
            uploadedImages: this.uploadedImages ? Object.keys(this.uploadedImages).length : 0,
            canvas: !!this.canvas
        });
        
        if (!this.uploadedImages) {
            console.log('⚠️ 没有上传的图片，退出拖拽检测');
            return;
        }
        
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        // 转换为模板坐标系（参考普通定制页面）
        const templateX = x / this.displayScale;
        const templateY = y / this.displayScale;
        
        console.log('鼠标点击位置:', {canvas: {x, y}, template: {x: templateX, y: templateY}});
        
        // 检查是否点击了上传的图片
        for (const [index, imageData] of Object.entries(this.uploadedImages)) {
            const match = imageData.match;
            const pos = match.optimal_position;
            const imgX = pos.x * this.displayScale;
            const imgY = pos.y * this.displayScale;
            const imgWidth = (pos.width || 300) * this.displayScale;
            const imgHeight = (pos.height || 300) * this.displayScale;
            
            // 检查是否点击了缩放手柄（使用Canvas坐标）
            const resizeHandle = this.getResizeHandle(x, y, imgX, imgY, imgWidth, imgHeight);
            if (resizeHandle && this.selectedImageIndex == index) {
                this.isResizing = true;
                this.resizeHandle = resizeHandle;
                this.selectedImageIndex = index;
                this.dragStart = {x: templateX, y: templateY}; // 使用模板坐标
                this.originalSize = {width: pos.width || 300, height: pos.height || 300};
                this.originalPosition = {x: pos.x, y: pos.y};
                this.canvas.style.cursor = this.getResizeCursor(resizeHandle);
                
                console.log(`开始缩放图片 ${parseInt(index) + 1} - ${resizeHandle}`);
                break;
            }
            // 检查是否点击了图片区域（使用Canvas坐标）
            else if (x >= imgX && x <= imgX + imgWidth && y >= imgY && y <= imgY + imgHeight) {
                this.selectedImageIndex = index;
                this.isDragging = true;
                this.dragStart = {x: templateX, y: templateY}; // 使用模板坐标
                this.canvas.style.cursor = 'move';
                
                // 重新渲染显示选中状态
                this.updatePreviewWithUploadedImages();
                
                console.log(`选中图片 ${parseInt(index) + 1}`);
                break;
            }
        }
        
        // 如果没有点击任何图片，清除选中状态
        if (!this.isDragging && !this.isResizing && this.selectedImageIndex !== null) {
            this.selectedImageIndex = null;
            this.updatePreviewWithUploadedImages();
        }
    }
    
    getResizeHandle(mouseX, mouseY, imgX, imgY, imgWidth, imgHeight) {
        const handleSize = 8;
        const tolerance = handleSize;
        
        // 检查四个角的手柄
        const handles = {
            'tl': {x: imgX, y: imgY}, // top-left
            'tr': {x: imgX + imgWidth, y: imgY}, // top-right
            'bl': {x: imgX, y: imgY + imgHeight}, // bottom-left
            'br': {x: imgX + imgWidth, y: imgY + imgHeight} // bottom-right
        };
        
        for (const [handle, pos] of Object.entries(handles)) {
            if (Math.abs(mouseX - pos.x) <= tolerance && Math.abs(mouseY - pos.y) <= tolerance) {
                return handle;
            }
        }
        
        return null;
    }
    
    getResizeCursor(handle) {
        switch (handle) {
            case 'tl':
            case 'br':
                return 'nw-resize';
            case 'tr':
            case 'bl':
                return 'ne-resize';
            default:
                return 'default';
        }
    }
    
    onCanvasMouseMove(e) {
        if (!this.isDragging && !this.isResizing) {
            // 悬停检测
            this.updateCursor(e);
            return;
        }
        
        if (this.selectedImageIndex === null) return;
        
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        // 转换为模板坐标系（参考普通定制页面）
        const templateX = x / this.displayScale;
        const templateY = y / this.displayScale;
        
        const imageData = this.uploadedImages[this.selectedImageIndex];
        const match = imageData.match;
        const pos = match.optimal_position;
        
        // 计算模板坐标系中的移动距离
        const deltaX = templateX - this.dragStart.x;
        const deltaY = templateY - this.dragStart.y;
        
        if (this.isResizing && this.resizeHandle) {
            // 缩放操作 - 使用模板坐标系
            const newSize = this.calculateNewSize(this.resizeHandle, deltaX, deltaY, pos);
            
            // 更新位置和尺寸
            pos.width = newSize.width;
            pos.height = newSize.height;
            pos.x = newSize.x;
            pos.y = newSize.y;
            
            console.log(`缩放中: 位置(${Math.round(pos.x)}, ${Math.round(pos.y)}) 尺寸${Math.round(pos.width)}×${Math.round(pos.height)}`);
        } else if (this.isDragging) {
            // 拖拽操作 - 使用模板坐标系
            pos.x += deltaX;
            pos.y += deltaY;
            
            console.log(`拖拽中: 位置(${Math.round(pos.x)}, ${Math.round(pos.y)})`);
        }
        
        // 更新拖拽起始点（模板坐标系）
        this.dragStart = {x: templateX, y: templateY};
        
        // 重新渲染
        this.updatePreviewWithUploadedImages();
    }
    
    calculateNewSize(handle, deltaX, deltaY, position) {
        const originalWidth = position.width || 300;
        const originalHeight = position.height || 300;
        
        let newWidth = originalWidth;
        let newHeight = originalHeight;
        let newX = position.x;
        let newY = position.y;
        
        // 按照普通定制页面的逻辑处理缩放
        switch (handle) {
            case 'tl': // 左上角
                newWidth = originalWidth - deltaX;
                newHeight = originalHeight - deltaY;
                newX = position.x + deltaX;
                newY = position.y + deltaY;
                break;
            case 'tr': // 右上角
                newWidth = originalWidth + deltaX;
                newHeight = originalHeight - deltaY;
                newY = position.y + deltaY;
                break;
            case 'bl': // 左下角
                newWidth = originalWidth - deltaX;
                newHeight = originalHeight + deltaY;
                newX = position.x + deltaX;
                break;
            case 'br': // 右下角
                newWidth = originalWidth + deltaX;
                newHeight = originalHeight + deltaY;
                break;
        }
        
        // 确保最小尺寸
        newWidth = Math.max(50, newWidth);
        newHeight = Math.max(50, newHeight);
        
        return {
            width: newWidth, 
            height: newHeight,
            x: newX,
            y: newY
        };
    }
    
    onCanvasMouseUp(e) {
        if (this.isResizing || this.isDragging) {
            console.log('操作完成');
        }
        
        this.isDragging = false;
        this.isResizing = false;
        this.resizeHandle = null;
        this.canvas.style.cursor = 'default';
        
        // 保持选中状态，不清除 selectedImageIndex
    }
    
    updateCursor(e) {
        if (!this.uploadedImages) return;
        
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        let cursor = 'default';
        
        for (const [index, imageData] of Object.entries(this.uploadedImages)) {
            const match = imageData.match;
            const pos = match.optimal_position;
            const imgX = pos.x * this.displayScale;
            const imgY = pos.y * this.displayScale;
            const imgWidth = (pos.width || 300) * this.displayScale;
            const imgHeight = (pos.height || 300) * this.displayScale;
            
            // 检查缩放手柄
            if (this.selectedImageIndex == index) {
                const resizeHandle = this.getResizeHandle(x, y, imgX, imgY, imgWidth, imgHeight);
                if (resizeHandle) {
                    cursor = this.getResizeCursor(resizeHandle);
                    break;
                }
            }
            
            // 检查图片区域
            if (x >= imgX && x <= imgX + imgWidth && y >= imgY && y <= imgY + imgHeight) {
                cursor = 'move';
                break;
            }
        }
        
        this.canvas.style.cursor = cursor;
    }
    
    adaptToNearestRegion(position, forceAdapt = false) {
        if (!this.currentRegions || this.currentRegions.length === 0) {
            console.log('⚠️ 没有可用的定制区域');
            return;
        }
        
        // 找到最近的定制区域
        let nearestRegion = null;
        let minDistance = Infinity;
        
        this.currentRegions.forEach(region => {
            const regionCenterX = region.x + region.width / 2;
            const regionCenterY = region.y + region.height / 2;
            const positionCenterX = position.x + (position.width || 300) / 2;
            const positionCenterY = position.y + (position.height || 300) / 2;
            
            const distance = Math.sqrt(
                Math.pow(regionCenterX - positionCenterX, 2) + 
                Math.pow(regionCenterY - positionCenterY, 2)
            );
            
            if (distance < minDistance) {
                minDistance = distance;
                nearestRegion = region;
            }
        });
        
        const adaptDistance = forceAdapt ? Infinity : 500;
        if (nearestRegion && minDistance < adaptDistance) {
            // 自动适配尺寸
            this.adaptSizeToRegion(position, nearestRegion);
            
            console.log(`✅ 适配到区域: ${nearestRegion.name} (距离: ${Math.round(minDistance)}像素)`);
        } else {
            console.log(`⚠️ 没有进行适配，最近距离: ${Math.round(minDistance)}像素`);
        }
    }
    
    adaptSizeToRegion(position, region) {
        const currentWidth = position.width || 300;
        const currentHeight = position.height || 300;
        
        // 按照您的需求进行尺寸适配
        if (currentWidth > region.width || currentHeight > region.height) {
            // 如果比定制区域大，则自适应为定制区域尺寸
            const scaleX = region.width / currentWidth;
            const scaleY = region.height / currentHeight;
            const scale = Math.min(scaleX, scaleY); // 保持比例
            
            position.width = Math.round(currentWidth * scale);
            position.height = Math.round(currentHeight * scale);
            
            console.log(`尺寸自适应: ${currentWidth}x${currentHeight} → ${position.width}x${position.height}`);
        }
        // 如果设置完成图片大小后依然无法占满定制区域，无需继续调整大小
        
        // 将图片居中放置在定制区域附近
        position.x = region.x + (region.width - position.width) / 2;
        position.y = region.y + (region.height - position.height) / 2;
        
        position.region_id = region.id;
    }
    
    manualAdaptToRegions() {
        if (!this.uploadedImages || Object.keys(this.uploadedImages).length === 0) {
            APP_UTILS.showError('请先上传定制图片');
            return;
        }
        
        if (!this.analysisResult || !this.analysisResult.positioning_result) {
            APP_UTILS.showError('请先进行智能分析');
            return;
        }
        
        let adaptedCount = 0;
        
        Object.keys(this.uploadedImages).forEach(index => {
            const imageData = this.uploadedImages[index];
            const match = imageData.match;
            const pos = match.optimal_position;
            
            // 重置为初始分析结果的位置和尺寸
            const originalMatch = this.analysisResult.positioning_result.matches[index];
            if (originalMatch && originalMatch.optimal_position) {
                const originalPos = originalMatch.optimal_position;
                
                // 恢复到初始分析的状态
                pos.x = originalPos.x;
                pos.y = originalPos.y;
                pos.width = originalPos.width;
                pos.height = originalPos.height;
                
                // 再次执行初始的自动适配逻辑
                this.adaptToNearestRegion(pos, true);
                
                console.log(`重置图片${parseInt(index) + 1}到初始分析状态并重新适配`);
                adaptedCount++;
            }
        });
        
        // 重新渲染
        this.updatePreviewWithUploadedImages();
        
        APP_UTILS.showSuccess(`已恢复 ${adaptedCount} 个图片到初始状态并重新适配`);
        
        console.log(`✅ 手动适配完成，共${adaptedCount}个图片`);
    }
    
    async exportIntelligentResult() {
        if (!this.analysisResult) {
            APP_UTILS.showError('请先进行智能分析');
            return;
        }
        
        if (!this.uploadedImages || Object.keys(this.uploadedImages).length === 0) {
            APP_UTILS.showError('请先上传定制图片');
            return;
        }
        
        // 获取用户输入的文件名
        const defaultName = `智能定位_${new Date().toLocaleDateString()}`;
        const fileName = prompt('请输入导出文件名（不需要扩展名）:', defaultName);
        if (!fileName) return; // 用户取消
        
        try {
            APP_UTILS.showLoading('导出智能布局结果...');
            
            // 准备上传的图片数据
            const uploadedImagesData = {};
            
            for (const [index, imageData] of Object.entries(this.uploadedImages)) {
                // 将文件转换为base64上传
                uploadedImagesData[index] = {
                    dataUrl: imageData.dataUrl,
                    filename: imageData.file.name,
                    match: imageData.match
                };
            }
            
            // 获取导出设置
            const exportFormat = $('#intelligentExportFormat').val() || 'tif';
            const preserveLayers = $('#intelligentPreserveLayers').is(':checked');
            
            const response = await APP_AJAX.post('/api/export_intelligent_layout', {
                template_id: this.currentTemplate.id,
                analysis_result: this.analysisResult,
                uploaded_images: uploadedImagesData,
                export_format: exportFormat,
                preserve_layers: preserveLayers,
                custom_filename: fileName,  // 添加自定义文件名
                layer_adjustments: this.layerColorAdjustments,  // 图层颜色调整
                image_rotations: this.imageRotations  // 图片旋转信息
            });
            
            if (response.success) {
                APP_UTILS.showSuccess('智能布局导出成功');
                
                // 创建下载链接
                const link = document.createElement('a');
                link.href = response.download_url;
                link.download = response.export_path;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } else {
                APP_UTILS.showError(response.error || '导出失败');
            }
            
            APP_UTILS.hideLoading();
        } catch (error) {
            APP_UTILS.hideLoading();
            APP_UTILS.showError('导出失败: ' + (error.error || '未知错误'));
        }
    }
    
    loadTemplatePreview() {
        if (!this.currentTemplate) return;
        
        console.log('开始加载模板预览:', this.currentTemplate.name);
        
        // 初始化预览画布
        this.initPreviewCanvas();
        
        // 加载模板背景图片
        const img = new Image();
        
        img.onload = () => {
            console.log('模板背景图片加载成功');
            this.templateBackgroundImage = img;
            this.renderTemplatePreview();
        };
        
        img.onerror = (e) => {
            console.error('模板背景图片加载失败:', e);
            this.renderTemplatePreview(); // 即使加载失败也显示基本预览
        };
        
        // 加载模板图片，添加时间戳避免缓存
        img.src = `/template_image/${this.currentTemplate.id}?t=${Date.now()}`;
    }
    
    initPreviewCanvas() {
        const canvasElement = document.getElementById('intelligentCanvas');
        if (!canvasElement) {
            console.error('找不到intelligentCanvas元素');
            return;
        }
        
        // 如果canvas变了或者是第一次初始化，重新设置事件监听器
        if (this.canvas !== canvasElement) {
            this.canvas = canvasElement;
            this.ctx = this.canvas.getContext('2d');
            
            // 不重复添加事件监听器，防止冲突
            // this.addCanvasDragFunctionality();
            
            console.log('预览画布重新初始化成功');
        }
        
        if (!this.canvas || !this.currentTemplate) return;
        
        // 设置画布尺寸
        const maxWidth = 500;
        const maxHeight = 400;
        const templateWidth = this.currentTemplate.width;
        const templateHeight = this.currentTemplate.height;
        
        const scaleX = maxWidth / templateWidth;
        const scaleY = maxHeight / templateHeight;
        this.displayScale = Math.min(scaleX, scaleY, 1);
        
        this.canvas.width = templateWidth * this.displayScale;
        this.canvas.height = templateHeight * this.displayScale;
        
        // 设置CSS尺寸
        this.canvas.style.width = this.canvas.width + 'px';
        this.canvas.style.height = this.canvas.height + 'px';
        
        console.log('预览画布尺寸设置:', {
            template: `${templateWidth}x${templateHeight}`,
            canvas: `${this.canvas.width}x${this.canvas.height}`,
            scale: this.displayScale
        });
    }
    
    renderTemplatePreview() {
        if (!this.canvas || !this.ctx) {
            console.error('画布或上下文未初始化');
            return;
        }
        
        console.log('开始渲染模板预览');
        
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制背景
        this.ctx.fillStyle = '#f8f9fa';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制模板背景图片（保持原始状态）
        if (this.templateBackgroundImage) {
            try {
                // 直接绘制原始图片，不应用颜色调整
                this.ctx.drawImage(
                    this.templateBackgroundImage,
                    0, 0,
                    this.canvas.width,
                    this.canvas.height
                );
                console.log('模板背景绘制成功（保持原始颜色）');
            } catch (error) {
                console.error('绘制模板背景失败:', error);
            }
        } else {
            // 没有背景图片时，显示模板信息
            this.ctx.fillStyle = '#6c757d';
            this.ctx.font = '16px Arial';
            this.ctx.textAlign = 'center';
            this.ctx.fillText(
                `${this.currentTemplate.name}`,
                this.canvas.width / 2,
                this.canvas.height / 2 - 10
            );
            this.ctx.fillText(
                `${this.currentTemplate.width} x ${this.currentTemplate.height}`,
                this.canvas.width / 2,
                this.canvas.height / 2 + 10
            );
            this.ctx.textAlign = 'left';
        }
        
        // 绘制定制区域
        if (this.currentRegions && this.currentRegions.length > 0) {
            this.ctx.strokeStyle = '#007bff';
            this.ctx.lineWidth = 2;
            this.ctx.setLineDash([5, 5]);
            
            this.currentRegions.forEach(region => {
                const x = region.x * this.displayScale;
                const y = region.y * this.displayScale;
                const width = region.width * this.displayScale;
                const height = region.height * this.displayScale;
                
                this.ctx.strokeRect(x, y, width, height);
                
                // 绘制区域标签
                this.ctx.fillStyle = '#007bff';
                this.ctx.font = `${Math.max(10, 12 * this.displayScale)}px Arial`;
                this.ctx.fillText(region.name, x + 5, y + 15);
            });
            
            this.ctx.setLineDash([]);
        }
        
        // 显示预览区域
        $('#previewPlaceholder').hide();
        $('#previewCanvas').show();
        
        // 只在首次初始化时添加拖拽功能
        if (!this.dragFunctionalityAdded) {
            this.addCanvasDragFunctionality();
            this.dragFunctionalityAdded = true;
        }
        
        console.log('模板预览渲染完成');
    }
    
    handleBatchFileSelection(files) {
        console.log(`选择了${files.length}个文件进行批量上传`);
        
        // 检查文件数量是否合理
        const maxMatches = this.analysisResult?.positioning_result?.matches?.length || 0;
        if (files.length > maxMatches) {
            APP_UTILS.showWarning(`您选择了${files.length}个文件，但只检测到${maxMatches}个定制区域。多余的文件将被忽略。`);
        }
        
        // 验证文件格式
        const validFiles = [];
        const validExtensions = ['png', 'jpg', 'jpeg', 'gif', 'webp'];
        
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const extension = file.name.split('.').pop().toLowerCase();
            
            if (validExtensions.includes(extension)) {
                if (file.size > 10 * 1024 * 1024) { // 10MB限制
                    APP_UTILS.showWarning(`文件 ${file.name} 过大，已忽略`);
                    continue;
                }
                validFiles.push(file);
            } else {
                APP_UTILS.showWarning(`文件 ${file.name} 格式不支持，已忽略`);
            }
        }
        
        if (validFiles.length === 0) {
            APP_UTILS.showError('没有有效的图片文件');
            return;
        }
        
        // 保存文件数组供后续处理
        this.batchFiles = validFiles;
        
        // 启用处理按钮
        $('#processBatchUpload').prop('disabled', false);
        
        // 显示文件信息
        const fileInfo = validFiles.map(f => f.name).join(', ');
        APP_UTILS.showSuccess(`已选择${validFiles.length}个文件: ${fileInfo.length > 50 ? fileInfo.substring(0, 50) + '...' : fileInfo}`);
    }
    
    async processBatchUpload() {
        if (!this.batchFiles || this.batchFiles.length === 0) {
            APP_UTILS.showError('请先选择要上传的文件');
            return;
        }
        
        if (!this.analysisResult?.positioning_result?.matches) {
            APP_UTILS.showError('没有可用的定制区域');
            return;
        }
        
        try {
            APP_UTILS.showLoading('正在处理批量上传...');
            
            const matches = this.analysisResult.positioning_result.matches;
            const uploadPromises = [];
            
            // 为每个文件创建上传任务
            for (let i = 0; i < Math.min(this.batchFiles.length, matches.length); i++) {
                const file = this.batchFiles[i];
                const match = matches[i];
                
                uploadPromises.push(this.processIndividualUpload(file, match, i));
            }
            
            // 并行处理所有上传
            const results = await Promise.all(uploadPromises);
            
            // 更新上传状态
            let successCount = 0;
            results.forEach((result, index) => {
                if (result.success) {
                    successCount++;
                    // 更新对应区域的显示
                    this.updateUploadDisplay(index, result.dataUrl, result.file.name);
                } else {
                    console.error(`文件 ${this.batchFiles[index].name} 上传失败:`, result.error);
                }
            });
            
            APP_UTILS.hideLoading();
            
            if (successCount === results.length) {
                APP_UTILS.showSuccess(`批量上传完成！成功上传${successCount}个文件`);
            } else {
                APP_UTILS.showWarning(`批量上传完成，成功${successCount}个，失败${results.length - successCount}个`);
            }
            
            // 重新渲染预览
            this.renderIntelligentPreview();
            
            // 启用导出功能
            $('#exportIntelligentResult').prop('disabled', false);
            
        } catch (error) {
            APP_UTILS.hideLoading();
            APP_UTILS.showError('批量上传失败: ' + error.message);
            console.error('批量上传错误:', error);
        }
    }
    
    async processIndividualUpload(file, match, index) {
        return new Promise((resolve) => {
            const reader = new FileReader();
            
            reader.onload = (e) => {
                try {
                    const dataUrl = e.target.result;
                    
                    // 验证图片
                    const img = new Image();
                    img.onload = () => {
                        // 存储上传的图片数据
                        if (!this.uploadedImages) {
                            this.uploadedImages = {};
                        }
                        
                        this.uploadedImages[index] = {
                            dataUrl: dataUrl,
                            file: file,
                            match: match,
                            dimensions: {
                                width: img.width,
                                height: img.height
                            },
                            scaleX: 1.0,
                            scaleY: 1.0
                        };
                        
                        resolve({
                            success: true,
                            dataUrl: dataUrl,
                            file: file
                        });
                    };
                    
                    img.onerror = () => {
                        resolve({
                            success: false,
                            error: '图片格式无效'
                        });
                    };
                    
                    img.src = dataUrl;
                    
                } catch (error) {
                    resolve({
                        success: false,
                        error: error.message
                    });
                }
            };
            
            reader.onerror = () => {
                resolve({
                    success: false,
                    error: '文件读取失败'
                });
            };
            
            reader.readAsDataURL(file);
        });
    }
    
    updateUploadDisplay(index, dataUrl, fileName) {
        // 更新单个上传区域的显示
        const previewElement = $(`#preview_${index}`);
        if (previewElement.length > 0) {
            previewElement.find('img').attr('src', dataUrl);
            previewElement.show();
            
            // 添加文件名显示
            if (!previewElement.find('.file-name').length) {
                previewElement.append(`<div class="file-name mt-1"><small class="text-muted">${fileName}</small></div>`);
            } else {
                previewElement.find('.file-name small').text(fileName);
            }
        }
        
        // 更新输入框状态
        $(`#customImage_${index}`).closest('.upload-entry').addClass('uploaded');
    }
    
    // ========== 区域切换控制功能 ==========
    
    initRegionSwitchControl() {
        const matches = this.analysisResult?.positioning_result?.matches;
        if (!matches || matches.length <= 1) {
            $('#regionSwitchCard').hide();
            return;
        }
        
        // 初始化切换状态
        this.currentRegionIndex = 0;
        this.totalRegions = matches.length;
        
        // 显示区域切换卡片
        $('#regionSwitchCard').show();
        
        // 更新显示
        this.updateRegionSwitchDisplay();
    }
    
    updateRegionSwitchDisplay() {
        const matches = this.analysisResult?.positioning_result?.matches;
        if (!matches || this.currentRegionIndex >= matches.length) {
            return;
        }
        
        const currentMatch = matches[this.currentRegionIndex];
        const regionNumber = this.currentRegionIndex + 1;
        
        // 更新区域信息
        $('#currentRegionInfo').text(`区域 ${regionNumber} / ${this.totalRegions}`);
        $('#currentRegionName').text(currentMatch.suggested_part || `图片 ${regionNumber}`);
        $('#currentRegionPosition').text(`位置: (${currentMatch.optimal_position.x}, ${currentMatch.optimal_position.y})`);
        
        // 更新按钮状态
        $('#prevRegionBtn').prop('disabled', this.currentRegionIndex === 0);
        $('#nextRegionBtn').prop('disabled', this.currentRegionIndex === this.totalRegions - 1);
        
        // 检查当前区域是否有上传的图片
        const hasImage = this.uploadedImages && this.uploadedImages[this.currentRegionIndex];
        $('#removeCurrentImage').prop('disabled', !hasImage);
        
        // 高亮当前区域（如果画布存在）
        this.highlightRegionInCanvas(this.currentRegionIndex);
    }
    
    switchToPreviousRegion() {
        if (this.currentRegionIndex > 0) {
            this.currentRegionIndex--;
            this.updateRegionSwitchDisplay();
        }
    }
    
    switchToNextRegion() {
        if (this.currentRegionIndex < this.totalRegions - 1) {
            this.currentRegionIndex++;
            this.updateRegionSwitchDisplay();
        }
    }
    
    highlightCurrentRegion() {
        const matches = this.analysisResult?.positioning_result?.matches;
        if (!matches || !this.canvas) {
            APP_UTILS.showError('无法高亮显示区域');
            return;
        }
        
        const currentMatch = matches[this.currentRegionIndex];
        
        // 重新渲染画布
        this.renderIntelligentPreview();
        
        // 添加高亮效果
        setTimeout(() => {
            this.highlightRegionInCanvas(this.currentRegionIndex, true);
        }, 100);
        
        APP_UTILS.showSuccess(`已高亮显示区域 ${this.currentRegionIndex + 1}: ${currentMatch.suggested_part}`);
    }
    
    highlightRegionInCanvas(regionIndex, animate = false) {
        if (!this.canvas || !this.ctx) return;
        
        const matches = this.analysisResult?.positioning_result?.matches;
        if (!matches || regionIndex >= matches.length) return;
        
        const match = matches[regionIndex];
        const pos = match.optimal_position;
        
        // 保存当前绘图状态
        this.ctx.save();
        
        // 设置高亮样式
        this.ctx.strokeStyle = animate ? '#ff0000' : '#ffc107';
        this.ctx.lineWidth = animate ? 3 : 2;
        this.ctx.setLineDash(animate ? [10, 5] : [5, 5]);
        
        // 绘制高亮框
        this.ctx.strokeRect(pos.x, pos.y, pos.width || 300, pos.height || 300);
        
        // 如果是动画模式，添加标签
        if (animate) {
            this.ctx.fillStyle = '#ff0000';
            this.ctx.font = '14px Arial';
            this.ctx.fillText(`区域 ${regionIndex + 1}`, pos.x, pos.y - 5);
        }
        
        // 恢复绘图状态
        this.ctx.restore();
    }
    
    replaceCurrentImage() {
        // 创建一个隐藏的文件输入
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = '.png,.jpg,.jpeg,.gif,.webp';
        fileInput.style.display = 'none';
        
        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                // 处理单个文件上传到当前区域
                this.handleSingleImageReplace(file, this.currentRegionIndex);
            }
            // 清理临时元素
            document.body.removeChild(fileInput);
        });
        
        document.body.appendChild(fileInput);
        fileInput.click();
    }
    
    async handleSingleImageReplace(file, regionIndex) {
        try {
            APP_UTILS.showLoading('正在替换图片...');
            
            const matches = this.analysisResult?.positioning_result?.matches;
            if (!matches || regionIndex >= matches.length) {
                throw new Error('无效的区域索引');
            }
            
            const match = matches[regionIndex];
            const result = await this.processIndividualUpload(file, match, regionIndex);
            
            if (result.success) {
                this.updateUploadDisplay(regionIndex, result.dataUrl, result.file.name);
                this.renderIntelligentPreview();
                this.updateRegionSwitchDisplay();
                
                APP_UTILS.showSuccess(`区域 ${regionIndex + 1} 的图片已成功替换`);
                
                // 启用导出功能
                $('#exportIntelligentResult').prop('disabled', false);
            } else {
                throw new Error(result.error || '图片处理失败');
            }
            
        } catch (error) {
            APP_UTILS.showError('替换图片失败: ' + error.message);
            console.error('图片替换错误:', error);
        } finally {
            APP_UTILS.hideLoading();
        }
    }
    
    removeCurrentImage() {
        const regionIndex = this.currentRegionIndex;
        
        if (!this.uploadedImages || !this.uploadedImages[regionIndex]) {
            APP_UTILS.showError('当前区域没有图片可以移除');
            return;
        }
        
        // 确认删除
        if (!confirm(`确定要移除区域 ${regionIndex + 1} 的图片吗？`)) {
            return;
        }
        
        try {
            // 移除上传的图片数据
            delete this.uploadedImages[regionIndex];
            
            // 清除显示
            const previewElement = $(`#preview_${regionIndex}`);
            if (previewElement.length > 0) {
                previewElement.hide();
                previewElement.find('img').attr('src', '');
                previewElement.find('.file-name').remove();
            }
            
            // 清除上传状态
            $(`#customImage_${regionIndex}`).val('').closest('.upload-entry').removeClass('uploaded');
            
            // 重新渲染预览
            this.renderIntelligentPreview();
            
            // 更新切换显示
            this.updateRegionSwitchDisplay();
            
            APP_UTILS.showSuccess(`已移除区域 ${regionIndex + 1} 的图片`);
            
        } catch (error) {
            APP_UTILS.showError('移除图片失败: ' + error.message);
            console.error('移除图片错误:', error);
        }
    }
    
    // ========== 底板图层管理功能 ==========
    
    displayTemplateLayers() {
        const container = $('#templateLayers');
        
        if (!this.templateLayers || this.templateLayers.length === 0) {
            container.html(`
                <div class="text-muted text-center py-3">
                    <i class="bi bi-layers"></i>
                    <div>未检测到图层信息</div>
                </div>
            `);
            $('#layerManagementCard').hide();
            return;
        }
        
        let html = '';
        this.templateLayers.forEach((layer, index) => {
            const isSelected = index === this.selectedLayerIndex;
            const colorAdjustment = this.layerColorAdjustments[index];
            const isModified = colorAdjustment && colorAdjustment.color && colorAdjustment.color !== '#ffffff';
            
            // 计算背景色
            let backgroundColor = '#f8f9fa'; // 默认背景色
            let textColor = '#212529'; // 默认文字色
            
            if (isModified) {
                backgroundColor = colorAdjustment.color;
                
                // 根据背景色亮度调整文字颜色
                const rgb = this.hexToRgb(backgroundColor);
                const brightness = (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
                textColor = brightness > 128 ? '#212529' : '#ffffff';
                
                console.log(`图层 ${index} (${layer.name}) 设置颜色: ${backgroundColor}, 文字色: ${textColor}`);
            }
            
            html += `
                <div class="layer-item ${isSelected ? 'selected' : ''} ${isModified ? 'modified' : ''}" 
                     data-layer-index="${index}"
                     style="background-color: ${backgroundColor}; color: ${textColor};">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <div class="fw-medium">${layer.name}</div>
                            <small class="text-muted" style="color: ${textColor}; opacity: 0.7;">${layer.type} | ${layer.visible ? '可见' : '隐藏'}</small>
                        </div>
                        <div class="text-end">
                            <small class="text-muted" style="color: ${textColor}; opacity: 0.7;">${layer.opacity}/255</small>
                            ${isModified ? `<i class="bi bi-palette ms-1" style="color: ${textColor};"></i>` : ''}
                        </div>
                    </div>
                </div>
            `;
        });
        
        container.html(html);
        $('#layerManagementCard').show();
        
        // 绑定图层点击事件
        $('.layer-item').on('click', (e) => {
            const layerIndex = parseInt($(e.currentTarget).data('layer-index'));
            this.selectLayer(layerIndex);
        });
    }
    
    selectLayer(layerIndex) {
        this.selectedLayerIndex = layerIndex;
        
        // 更新图层显示
        this.displayTemplateLayers();
        
        // 显示颜色调整面板
        if (layerIndex >= 0 && layerIndex < this.templateLayers.length) {
            const layer = this.templateLayers[layerIndex];
            $('#selectedLayerName').text(layer.name);
            
            // 加载当前图层的颜色设置
            const colorSetting = this.layerColorAdjustments[layerIndex] || {
                color: '#ffffff'
            };
            
            $('#layerColorPicker').val(colorSetting.color);
            $('#layerColorInput').val(colorSetting.color);
            
            $('#layerColorPanel').show();
        } else {
            $('#layerColorPanel').hide();
        }
    }
    
    
    previewLayerColorChanges() {
        if (this.selectedLayerIndex < 0) return;
        
        // 获取当前颜色设置
        const colorSetting = {
            color: $('#layerColorPicker').val()
        };
        
        // 临时保存颜色设置用于预览
        this.layerColorAdjustments[this.selectedLayerIndex] = colorSetting;
        
        // 只更新图层显示，不重新渲染整个预览 - 已隐藏
        // this.displayTemplateLayers();
        
        console.log('预览图层颜色调整:', colorSetting);
    }
    
    applyLayerColorChanges() {
        if (this.selectedLayerIndex < 0) {
            APP_UTILS.showError('请先选择要调整的图层');
            return;
        }
        
        const colorSetting = {
            color: $('#layerColorPicker').val()
        };
        
        // 永久保存颜色设置
        this.layerColorAdjustments[this.selectedLayerIndex] = colorSetting;
        
        // 更新图层显示状态 - 已隐藏
        // this.displayTemplateLayers();
        
        APP_UTILS.showSuccess(`已设置图层"${this.templateLayers[this.selectedLayerIndex].name}"的显示颜色: ${colorSetting.color}`);
        
        console.log('应用图层颜色设置:', this.selectedLayerIndex, colorSetting);
    }
    
    resetLayerColorChanges() {
        if (this.selectedLayerIndex < 0) return;
        
        // 重置颜色值
        $('#layerColorPicker').val('#ffffff');
        $('#layerColorInput').val('#ffffff');
        
        // 移除保存的调整
        delete this.layerColorAdjustments[this.selectedLayerIndex];
        
        // 更新显示 - 已隐藏
        // this.displayTemplateLayers();
        
        APP_UTILS.showSuccess('已重置图层颜色');
    }
    
    // ========== 图片交互功能 ==========
    
    onCanvasMouseDown(e) {
        if (!this.analysisResult?.positioning_result?.matches) return;
        
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        // 转换为画布坐标
        const canvasX = x * (this.canvas.width / rect.width);
        const canvasY = y * (this.canvas.height / rect.height);
        
        // 检查点击是否在某个图片区域内
        const matches = this.analysisResult.positioning_result.matches;
        let selectedIndex = -1;
        
        for (let i = 0; i < matches.length; i++) {
            if (!this.uploadedImages[i]) continue; // 只处理已上传的图片
            
            const match = matches[i];
            const pos = match.optimal_position;
            const x_scaled = pos.x * this.displayScale;
            const y_scaled = pos.y * this.displayScale;
            const w_scaled = (pos.width || 300) * this.displayScale;
            const h_scaled = (pos.height || 300) * this.displayScale;
            
            if (canvasX >= x_scaled && canvasX <= x_scaled + w_scaled &&
                canvasY >= y_scaled && canvasY <= y_scaled + h_scaled) {
                selectedIndex = i;
                break;
            }
        }
        
        // 首先检查是否点击了缩放控制点
        if (this.selectedImageIndex >= 0) {
            const resizeHandle = this.getResizeHandle(canvasX, canvasY);
            if (resizeHandle) {
                this.isResizing = true;
                this.resizeMode = resizeHandle.handle;
                this.isDragging = true;
                this.dragStart = { x: canvasX, y: canvasY };
                return;
            }
        }
        
        if (selectedIndex >= 0) {
            this.selectedImageIndex = selectedIndex;
            this.isDragging = true;
            this.isRotating = e.ctrlKey; // Ctrl键旋转
            this.isResizing = false;
            this.resizeMode = null;
            this.dragStart = { x: canvasX, y: canvasY };
            
            this.selectImage(selectedIndex);
        } else {
            this.selectedImageIndex = -1;
            this.selectImage(-1);
        }
    }
    
    onCanvasMouseMove(e) {
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        const canvasX = x * (this.canvas.width / rect.width);
        const canvasY = y * (this.canvas.height / rect.height);
        
        // 如果正在拖拽
        if (this.isDragging && this.selectedImageIndex >= 0) {
            const deltaX = canvasX - this.dragStart.x;
            const deltaY = canvasY - this.dragStart.y;
            
            if (this.isResizing && this.resizeMode) {
                // 缩放模式
                this.handleImageResize(deltaX, deltaY);
                this.dragStart = { x: canvasX, y: canvasY };
            } else if (this.isRotating) {
                // 旋转模式
                const rotationDelta = deltaX * 0.5;
                this.rotateSelectedImage(rotationDelta);
                this.dragStart = { x: canvasX, y: canvasY };
            } else {
                // 拖拽模式
                this.moveSelectedImage(deltaX / this.displayScale, deltaY / this.displayScale);
                this.dragStart = { x: canvasX, y: canvasY };
            }
        } else {
            // 非拖拽状态，处理鼠标悬停效果
            this.handleMouseHover(canvasX, canvasY);
        }
    }
    
    handleMouseHover(canvasX, canvasY) {
        if (this.selectedImageIndex >= 0) {
            // 检查是否悬停在控制点上
            const resizeHandle = this.getResizeHandle(canvasX, canvasY);
            
            if (resizeHandle) {
                this.canvas.style.cursor = resizeHandle.cursor;
            } else {
                // 检查是否在图片内部
                const matches = this.analysisResult.positioning_result.matches;
                const match = matches[this.selectedImageIndex];
                const pos = match.optimal_position;
                const x_scaled = pos.x * this.displayScale;
                const y_scaled = pos.y * this.displayScale;
                const w_scaled = (pos.width || 300) * this.displayScale;
                const h_scaled = (pos.height || 300) * this.displayScale;
                
                if (canvasX >= x_scaled && canvasX <= x_scaled + w_scaled &&
                    canvasY >= y_scaled && canvasY <= y_scaled + h_scaled) {
                    this.canvas.style.cursor = 'move';
                } else {
                    this.canvas.style.cursor = 'default';
                }
            }
        } else {
            this.canvas.style.cursor = 'crosshair';
        }
    }
    
    onCanvasMouseUp(e) {
        this.isDragging = false;
        this.isRotating = false;
        this.isResizing = false;
        this.resizeMode = null;
    }
    
    onCanvasMouseLeave(e) {
        this.isDragging = false;
        this.isRotating = false;
        this.isResizing = false;
        this.resizeMode = null;
        this.canvas.style.cursor = 'default';
    }
    
    moveSelectedImage(deltaX, deltaY) {
        if (this.selectedImageIndex < 0) return;
        
        const matches = this.analysisResult.positioning_result.matches;
        const match = matches[this.selectedImageIndex];
        
        // 更新位置
        match.optimal_position.x += deltaX;
        match.optimal_position.y += deltaY;
        
        // 限制在画布范围内
        match.optimal_position.x = Math.max(0, Math.min(match.optimal_position.x, 
            this.currentTemplate.width - (match.optimal_position.width || 300)));
        match.optimal_position.y = Math.max(0, Math.min(match.optimal_position.y, 
            this.currentTemplate.height - (match.optimal_position.height || 300)));
        
        // 更新显示
        $('#selectedImagePosition').text(`(${Math.round(match.optimal_position.x)}, ${Math.round(match.optimal_position.y)})`);
        
        // 重新渲染
        this.renderIntelligentPreview();
    }
    
    selectImage(imageIndex) {
        this.selectedImageIndex = imageIndex;
        
        if (imageIndex >= 0) {
            const match = this.analysisResult.positioning_result.matches[imageIndex];
            
            // 显示图片信息
            $('#selectedImageIndex').text(imageIndex + 1);
            $('#selectedImagePosition').text(`(${match.optimal_position.x}, ${match.optimal_position.y})`);
            
            // 显示当前旋转角度
            const rotation = this.imageRotations[imageIndex] || 0;
            $('#selectedImageRotation').text(rotation + '°');
            
            // 显示信息覆盖层和旋转控制器
            $('#imageInfoOverlay').show();
            
            // 确保旋转控制器在预览画布内部显示
            const canvasContainer = $('#previewCanvas');
            if (canvasContainer.find('#rotationControls').length === 0) {
                // 如果旋转控制器不在画布容器内，移动它
                $('#rotationControls').appendTo(canvasContainer);
            }
            $('#rotationControls').show();
            
            APP_UTILS.showSuccess(`已选择图片 ${imageIndex + 1}: ${match.suggested_part}`);
        } else {
            // 取消选择
            $('#imageInfoOverlay').hide();
            $('#rotationControls').hide();
        }
        
        // 重新渲染以显示选择状态
        this.renderIntelligentPreview();
        
        // 更新区域切换控制器
        if (imageIndex >= 0) {
            this.currentRegionIndex = imageIndex;
            this.updateRegionSwitchDisplay();
        }
    }
    
    rotateSelectedImage(angle) {
        if (this.selectedImageIndex < 0) {
            APP_UTILS.showError('请先选择要旋转的图片');
            return;
        }
        
        // 更新旋转角度
        const currentRotation = this.imageRotations[this.selectedImageIndex] || 0;
        const newRotation = (currentRotation + angle) % 360;
        this.imageRotations[this.selectedImageIndex] = newRotation;
        
        // 更新显示
        $('#selectedImageRotation').text(newRotation + '°');
        
        // 重新渲染
        this.renderIntelligentPreview();
        
        console.log(`旋转图片 ${this.selectedImageIndex + 1}: ${newRotation}°`);
    }
    
    resetSelectedImageRotation() {
        if (this.selectedImageIndex < 0) return;
        
        this.imageRotations[this.selectedImageIndex] = 0;
        $('#selectedImageRotation').text('0°');
        
        this.renderIntelligentPreview();
        
        APP_UTILS.showSuccess('已重置图片旋转');
    }
    
    // ========== 图片缩放功能 ==========
    
    drawResizeHandles(x, y, width, height) {
        const handleSize = 8;
        this.ctx.fillStyle = '#ffc107';
        this.ctx.strokeStyle = '#ffffff';
        this.ctx.lineWidth = 1;
        this.ctx.setLineDash([]);
        
        // 更新控制点位置（用于后续检测）
        this.controlPoints = [
            { x: x - handleSize/2, y: y - handleSize/2, handle: 'nw', cursor: 'nw-resize' },
            { x: x + width - handleSize/2, y: y - handleSize/2, handle: 'ne', cursor: 'ne-resize' },
            { x: x - handleSize/2, y: y + height - handleSize/2, handle: 'sw', cursor: 'sw-resize' },
            { x: x + width - handleSize/2, y: y + height - handleSize/2, handle: 'se', cursor: 'se-resize' },
            { x: x + width/2 - handleSize/2, y: y - handleSize/2, handle: 'n', cursor: 'n-resize' },
            { x: x + width - handleSize/2, y: y + height/2 - handleSize/2, handle: 'e', cursor: 'e-resize' },
            { x: x + width/2 - handleSize/2, y: y + height - handleSize/2, handle: 's', cursor: 's-resize' },
            { x: x - handleSize/2, y: y + height/2 - handleSize/2, handle: 'w', cursor: 'w-resize' }
        ];
        
        // 绘制控制点
        this.controlPoints.forEach(point => {
            this.ctx.fillRect(point.x, point.y, handleSize, handleSize);
            this.ctx.strokeRect(point.x, point.y, handleSize, handleSize);
        });
    }
    
    getResizeHandle(canvasX, canvasY) {
        if (!this.controlPoints) return null;
        
        const tolerance = 12;
        
        for (let point of this.controlPoints) {
            if (canvasX >= point.x - tolerance/2 && canvasX <= point.x + 8 + tolerance/2 &&
                canvasY >= point.y - tolerance/2 && canvasY <= point.y + 8 + tolerance/2) {
                return point;
            }
        }
        
        return null;
    }
    
    handleImageResize(deltaX, deltaY) {
        if (this.selectedImageIndex < 0 || !this.resizeMode) return;
        
        const matches = this.analysisResult.positioning_result.matches;
        const match = matches[this.selectedImageIndex];
        const imageData = this.uploadedImages[this.selectedImageIndex];
        
        if (!imageData) return;
        
        const currentWidth = (match.optimal_position.width || 300) * (imageData.scaleX || 1.0);
        const currentHeight = (match.optimal_position.height || 300) * (imageData.scaleY || 1.0);
        
        let newWidth = currentWidth;
        let newHeight = currentHeight;
        let newX = match.optimal_position.x;
        let newY = match.optimal_position.y;
        
        // 根据缩放模式调整尺寸
        switch (this.resizeMode) {
            case 'se': // 右下角
                newWidth = Math.max(50, currentWidth + deltaX / this.displayScale);
                newHeight = Math.max(50, currentHeight + deltaY / this.displayScale);
                break;
            case 'sw': // 左下角
                newWidth = Math.max(50, currentWidth - deltaX / this.displayScale);
                newHeight = Math.max(50, currentHeight + deltaY / this.displayScale);
                newX = match.optimal_position.x + deltaX / this.displayScale;
                break;
            case 'ne': // 右上角
                newWidth = Math.max(50, currentWidth + deltaX / this.displayScale);
                newHeight = Math.max(50, currentHeight - deltaY / this.displayScale);
                newY = match.optimal_position.y + deltaY / this.displayScale;
                break;
            case 'nw': // 左上角
                newWidth = Math.max(50, currentWidth - deltaX / this.displayScale);
                newHeight = Math.max(50, currentHeight - deltaY / this.displayScale);
                newX = match.optimal_position.x + deltaX / this.displayScale;
                newY = match.optimal_position.y + deltaY / this.displayScale;
                break;
            case 'e': // 右边
                newWidth = Math.max(50, currentWidth + deltaX / this.displayScale);
                break;
            case 'w': // 左边
                newWidth = Math.max(50, currentWidth - deltaX / this.displayScale);
                newX = match.optimal_position.x + deltaX / this.displayScale;
                break;
            case 's': // 下边
                newHeight = Math.max(50, currentHeight + deltaY / this.displayScale);
                break;
            case 'n': // 上边
                newHeight = Math.max(50, currentHeight - deltaY / this.displayScale);
                newY = match.optimal_position.y + deltaY / this.displayScale;
                break;
        }
        
        // 更新缩放比例
        const baseWidth = match.optimal_position.width || 300;
        const baseHeight = match.optimal_position.height || 300;
        imageData.scaleX = newWidth / baseWidth;
        imageData.scaleY = newHeight / baseHeight;
        
        // 更新位置
        match.optimal_position.x = newX;
        match.optimal_position.y = newY;
        
        // 重新渲染
        this.renderIntelligentPreview();
        
        console.log(`缩放图片 ${this.selectedImageIndex}: 比例(${imageData.scaleX.toFixed(2)}, ${imageData.scaleY.toFixed(2)})`);
    }
    
    // ========== 图层颜色显示功能 ==========
    // 注意：颜色调整现在只影响图层选项的背景显示，不影响实际底板
    
    hexToRgb(hex) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : {r: 0, g: 0, b: 0};
    }
    
    testNewFeatures() {
        console.log('🧪 测试新功能');
        
        // 测试图层信息
        console.log('图层信息:', this.templateLayers);
        console.log('颜色调整:', this.layerColorAdjustments);
        console.log('图片旋转:', this.imageRotations);
        console.log('上传图片:', this.uploadedImages);
        
        // 显示调试信息
        let debugInfo = '🔍 调试信息：\n\n';
        debugInfo += `图层数量: ${this.templateLayers ? this.templateLayers.length : 0}\n`;
        debugInfo += `颜色调整: ${Object.keys(this.layerColorAdjustments).length}\n`;
        debugInfo += `图片旋转: ${Object.keys(this.imageRotations).length}\n`;
        debugInfo += `上传图片: ${this.uploadedImages ? Object.keys(this.uploadedImages).length : 0}\n`;
        debugInfo += `选中图层: ${this.selectedLayerIndex}\n`;
        debugInfo += `选中图片: ${this.selectedImageIndex}\n`;
        
        // 添加颜色调整详情
        if (Object.keys(this.layerColorAdjustments).length > 0) {
            debugInfo += '\n📊 颜色调整详情:\n';
            Object.keys(this.layerColorAdjustments).forEach(layerIndex => {
                const adjustment = this.layerColorAdjustments[layerIndex];
                const layerName = this.templateLayers[layerIndex]?.name || `图层${layerIndex}`;
                debugInfo += `  ${layerName}: ${adjustment.color}\n`;
            });
        }
        
        alert(debugInfo);
        
        // 强制刷新图层显示 - 已隐藏
        // this.displayTemplateLayers();
        
        // 强制重新渲染
        this.renderIntelligentPreview();
    }
    
    resetAnalysis() {
        this.analysisResult = null;
        this.jsonData = null;
        this.batchFiles = null;
        this.uploadedImages = {};
        this.currentRegionIndex = 0;
        this.totalRegions = 0;
        this.selectedLayerIndex = -1;
        this.layerColorAdjustments = {};
        this.selectedImageIndex = -1;
        this.imageRotations = {};
        this.imageColorAdjustments = {};
        this.isDragging = false;
        this.isRotating = false;
        this.isResizing = false;
        this.resizeMode = null;
        this.controlPoints = [];
        
        $('#jsonFile').val('');
        $('#analysisResult').hide();
        $('#batchUploadSection').hide();
        $('#batchImageUpload').val('');
        $('#processBatchUpload').prop('disabled', true);
        $('#regionSwitchCard').hide();
        $('#layerManagementCard').hide();
        $('#layerColorPanel').hide();
        $('#imageControlGroup').hide();
        $('#imageInfoOverlay').hide();
        $('#rotationControls').hide();
        $('#previewCanvas').hide();
        $('#previewPlaceholder').show();
        $('#saveIntelligentProject').prop('disabled', true);
        $('#exportIntelligentResult').prop('disabled', true);
        $('#adaptToRegions').prop('disabled', true);
        
        this.displayGarmentParts();
        
        $('#detectedImages').html(`
            <div class="text-muted text-center py-3">
                <i class="bi bi-collection"></i>
                <div>暂无图片</div>
            </div>
        `);
        
        $('#suggestions').html(`
            <div class="text-muted text-center py-3">
                <i class="bi bi-magic"></i>
                <div>等待分析...</div>
            </div>
        `);
    }
}

// 初始化智能定位系统
$(document).ready(function() {
    console.log('✅ 初始化智能定位系统');
    
    try {
        window.intelligentPositioning = new IntelligentPositioning();
        console.log('✅ 智能定位系统初始化成功');
        
        // 检查URL参数，如果有template_id则自动选择
        const urlParams = new URLSearchParams(window.location.search);
        const templateId = urlParams.get('template_id');
        if (templateId) {
            console.log('检测到template_id参数:', templateId);
            $('#templateSelect').val(templateId).trigger('change');
            
            // 显示提示信息
            setTimeout(() => {
                APP_UTILS.showSuccess(`已自动选择底板，请上传JSON文件开始智能分析`);
            }, 500);
        }
    } catch (error) {
        console.error('❌ 智能定位系统初始化失败:', error);
        alert('系统初始化失败: ' + error.message);
    }
});
